package com.tzkyzj.tiremanagersystem.network;

import android.content.Context;
import android.util.Log;

import com.github.chrisbanes.photoview.BuildConfig;
import com.tzkyzj.tiremanagersystem.MyApplication;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    private static final String TAG = "ApiClient";
    public static final String BASE_URL = "http://120.55.37.146:8080/";
    private static Retrofit retrofit = null;
    private static SessionManager sessionManager;

    public static Retrofit getClient() {
        if (retrofit == null) {
            // 初始化 SessionManager
            Context context = MyApplication.getAppContext();
            if (context == null) {
                Log.e(TAG, "Application context 为 null，无法初始化 SessionManager");
                return null;
            }
            sessionManager = SessionManager.getInstance(context);

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

            // 添加 Cookie 拦截器 - 发送请求时添加 Cookie
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request original = chain.request();
                    Request.Builder requestBuilder = original.newBuilder();

                    // 添加保存的 Cookie
                    Set<String> cookies = sessionManager.getCookies();
                    if (!cookies.isEmpty()) {
                        StringBuilder cookieHeader = new StringBuilder();
                        for (String cookie : cookies) {
                            if (cookieHeader.length() > 0) {
                                cookieHeader.append("; ");
                            }
                            cookieHeader.append(cookie);
                        }
                        requestBuilder.header("Cookie", cookieHeader.toString());
                        Log.d(TAG, "发送 Cookie: " + cookieHeader.toString());
                    } else {
                        Log.w(TAG, "没有保存的 Cookie");
                    }

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });

            // 添加响应拦截器 - 接收响应时保存 Cookie
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Response response = chain.proceed(request);

                    // 保存服务器返回的 Cookie
                    if (response.headers("Set-Cookie") != null) {
                        Set<String> cookies = new HashSet<>();
                        for (String header : response.headers("Set-Cookie")) {
                            // 提取 Cookie 的主要部分（去除路径、过期时间等）
                            String cookie = header.split(";")[0];
                            cookies.add(cookie);
                            Log.d(TAG, "收到 Cookie: " + cookie);
                        }
                        if (!cookies.isEmpty()) {
                            sessionManager.saveCookies(cookies);
                        }
                    }

                    return response;
                }
            });

            // 添加日志拦截器
            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
                httpClient.addInterceptor(logging);
            }

            // 添加超时设置
            httpClient.connectTimeout(30, TimeUnit.SECONDS);
            httpClient.readTimeout(30, TimeUnit.SECONDS);
            httpClient.writeTimeout(30, TimeUnit.SECONDS);

            // 构建 Retrofit 实例
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(httpClient.build())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            Log.d(TAG, "Retrofit 实例已创建，使用 Cookie 认证");
        }
        return retrofit;
    }

    /**
     * 清除 Retrofit 实例和 Cookie
     */
    public static void clearClient() {
        retrofit = null;
        if (sessionManager != null) {
            sessionManager.clearCookies();
        }
        Log.d(TAG, "已清除 Retrofit 实例和 Cookie");
    }


    // 在 ApiClient.java 中添加
    public static OkHttpClient getOkHttpClient() {
        Context context = MyApplication.getAppContext();
        if (context == null) {
            Log.e(TAG, "Application context 为 null，无法初始化 SessionManager");
            return null;
        }

        SessionManager sessionManager = SessionManager.getInstance(context);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        // 添加 Cookie 拦截器 - 发送请求时添加 Cookie
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();

                // 添加保存的 Cookie
                Set<String> cookies = sessionManager.getCookies();
                if (!cookies.isEmpty()) {
                    StringBuilder cookieHeader = new StringBuilder();
                    for (String cookie : cookies) {
                        if (cookieHeader.length() > 0) {
                            cookieHeader.append("; ");
                        }
                        cookieHeader.append(cookie);
                    }
                    requestBuilder.header("Cookie", cookieHeader.toString());
                    Log.d(TAG, "Glide 发送 Cookie: " + cookieHeader.toString());
                } else {
                    Log.w(TAG, "Glide 没有保存的 Cookie");
                }

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

        // 添加响应拦截器 - 接收响应时保存 Cookie
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);

                // 保存服务器返回的 Cookie
                if (response.headers("Set-Cookie") != null) {
                    Set<String> cookies = new HashSet<>();
                    for (String header : response.headers("Set-Cookie")) {
                        String cookie = header.split(";")[0];
                        cookies.add(cookie);
                        Log.d(TAG, "Glide 收到 Cookie: " + cookie);
                    }
                    if (!cookies.isEmpty()) {
                        sessionManager.saveCookies(cookies);
                    }
                }

                return response;
            }
        });

        // 添加日志拦截器
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
            httpClient.addInterceptor(logging);
        }

        // 添加超时设置
        httpClient.connectTimeout(30, TimeUnit.SECONDS);
        httpClient.readTimeout(30, TimeUnit.SECONDS);
        httpClient.writeTimeout(30, TimeUnit.SECONDS);

        return httpClient.build();
    }

    /**
     * 调试 Cookie 状态
     */
    public static void debugCookies() {
        if (sessionManager != null) {
            sessionManager.debugCookies();
        } else {
            Log.w(TAG, "SessionManager 未初始化");
        }
    }
}